package com.shenmazong.send.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.amqp.core.MessageBuilderSupport;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.nio.charset.StandardCharsets;
import java.util.UUID;

/**
 * @author 军哥
 * @version 1.0
 * @description: TODO
 * @date 2022/2/8 15:55
 */

@RestController
@Slf4j
@Api(tags = "rabbitmq消息发送")
public class MqController {

    @Autowired
    RabbitTemplate rabbitTemplate;

    @ApiOperation(value = "发送消息")
    @PostMapping(value = "/sendMessage")
    public String sendMessage(@RequestParam("msg") String msg) {
        // 生成消息的唯一ID
        String msgId = UUID.randomUUID().toString();

        // 生成唯一ID后，放入消息中
        Message message = MessageBuilder.withBody(msg.getBytes(StandardCharsets.UTF_8))
                .setContentEncoding("UTF-8")
                .setMessageId(msgId).build();

        rabbitTemplate.convertAndSend("hello", message);
        log.info("sendMessage:" + msg);

        return msg;
    }
}
